package com.micro.magupe.cms.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

import com.micro.magupe.cms.security.CustomOAuth2AuthenticationManager;
import com.micro.magupe.cms.security.PermitAllUrlProperties;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    
    @Bean
    public PermitAllUrlProperties getPermitAllUrlProperties() {
        return new PermitAllUrlProperties();
    }
    
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		resources.resourceId("micro-magupe-cms").stateless(true);
		
		/**
		 * 自定义OAuth2AuthenticationManager，就是继承OAuth2AuthenticationManager重写其发放
		 * 主要是为了验证resourceId，因为源生代码OAuth2Authentication的属性storedRequest为空，但是userAuthentication属性是有resourceId的
		 */
		CustomOAuth2AuthenticationManager customOAuth2AuthenticationManager = new CustomOAuth2AuthenticationManager();
		resources.authenticationManager(customOAuth2AuthenticationManager);
	}
	
	@Override
    public void configure(HttpSecurity http) throws Exception {
		http
			.csrf().disable()
			.authorizeRequests().antMatchers(getPermitAllUrlProperties().getPermitall()).permitAll()
			.anyRequest().authenticated()
			.and()
			.formLogin()
            .and()
			.httpBasic();
    }
}
